package com.take.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.take.common.BaseContext;
import com.take.common.CustomException;
import com.take.dto.SetmealDto;
import com.take.entity.Setmeal;
import com.take.entity.SetmealDish;
import com.take.mapper.SetmealMapper;
import com.take.service.SetmealDishService;
import com.take.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     *
     * @param setmealDto
     */
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐，同时需要删除套餐和菜品的关联数据
     *
     * @param ids
     */
    @Transactional
    public void removeWithDish(List<Long> ids) {

        //【重点:管理员（currentId=1）或者套餐创建者，才能删除套餐】

        Long currentId = BaseContext.getCurrentId();
        // 如果不是管理员要删除套餐，则要//判断当前要删除的套餐，是否有非当前用户创建的，
        if (currentId != 1) {
            for (Long id : ids) {
                Setmeal thisSetmeal = this.getById(id);
                //如果用户不是管理员，但是套餐创建者，也能修改
                Long createUserId = thisSetmeal.getCreateUser();
                if (!createUserId.equals(currentId)) {
                    throw new CustomException("失败！当前套餐只能被创建者或者管理员删除");
                }
            }
        }

        //select count(*) from setmeal where id in (1,2,3) and status = 1
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus, 1);

        int count = this.count(queryWrapper);
        if (count > 0) {
            //如果不能删除，抛出一个业务异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }

        //如果可以删除，先删除套餐表中的数据---setmeal
        this.removeByIds(ids);

        //delete from setmeal_dish where setmeal_id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        //删除关系表中的数据----setmeal_dish
        setmealDishService.remove(lambdaQueryWrapper);
    }

    @Override
    public SetmealDto getByIdWithDishes(Long id) {
        //先查套餐信息
        Setmeal setmeal = this.getById(id);
        //接下来查询与套餐中包含的菜品
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper();
        lqw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(lqw);
        //构造dto对象
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        setmealDto.setSetmealDishes(setmealDishList);
        return setmealDto;
    }

    @Override
    public void updateWithSetmealDishes(SetmealDto setmealDto) {

        //【重点:管理员或者套餐创建者，才能修改套餐】
        //判断当前修改套餐的人是否是admin，如果是admin，则能修改
        Long setmealId = setmealDto.getId();
        Setmeal thisSetmeal = this.getById(setmealId);
        Long currentId = BaseContext.getCurrentId();
        if (currentId != 1) {
            //如果用户不是管理员，但是套餐创建者，也能修改
            Long createUserId = thisSetmeal.getCreateUser();
            if (!createUserId.equals(currentId)) {
                throw new CustomException("失败！当前套餐只能被创建者或者管理员修改");
            }
        }

        //更新setmeal表基本信息
        this.updateById(setmealDto);

        //清理当前菜品已经关联的菜品---setmeal_dish表的delete操作
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());

        setmealDishService.remove(queryWrapper);

        //添加当前提交过来的菜品数据---setmeal_dish表的insert操作
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);
    }
}
